//
//  HJComposeView.swift
//  Weibo
//
//  Created by 韩佳 on 16/4/25.
//  Copyright © 2016年 ddg. All rights reserved.
//

import UIKit
import pop

class HJComposeView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //按钮信息模型数组
    private var modelArray:[HJComposeMenuItemInfo]?{
        return itemsInfo()
    }
    //按钮数组
    private lazy var menuButtons: [HJComposeMenuButton] = []
    //目标控制器
    private var targetVc:UIViewController?
    func show(targetVc: UIViewController?){
        targetVc?.view.addSubview(self)
        self.targetVc = targetVc
    }
    private func setupUI(){
        backgroundColor = UIColor.cyanColor()
        frame = UIScreen.mainScreen().bounds
        let image = UIImage.getScreenShot().applyLightEffect()
        let imageView = UIImageView(image: image)
        addSubview(imageView)
        
        //添加控件
        addSubview(sloganImage)
        
        
        //约束
        sloganImage.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
        //添加按钮
        addMenuButton()
    }
    private func addMenuButton(){
        
        let itemW:CGFloat = 80
        let itemH:CGFloat = 100
        let itemMargin:CGFloat = (ScreenWidth - itemW * 3) / 4
        
        for (i,value) in modelArray!.enumerate() {
            let button = HJComposeMenuButton(btnColor: UIColor.darkGrayColor(), fontSize: 14)
            button.addTarget(self, action: "menuButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            button.setImage(UIImage(named: value.icon!), forState: UIControlState.Normal)
            button.setTitle(value.title, forState: UIControlState.Normal)
            button.frame.size = CGSize(width: itemW, height: itemH)
            menuButtons.append(button)
            button.tag = i
            addSubview(button)
            //行
            let row = i / 3
            let col = i % 3
            button.frame.origin.x = itemW * CGFloat(col) + itemMargin * CGFloat(col + 1)
            button.frame.origin.y = itemH * CGFloat(row) + 10 * CGFloat(row) + ScreenHeight
        }
    
        
    }
    //按钮点击事件
    @objc private func menuButtonClick(sender:HJComposeMenuButton){
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            for value in self.menuButtons{
                value.alpha = 0.01
                if sender == value{
                    sender.transform = CGAffineTransformMakeScale(2, 2)
                }else{
                    value.transform = CGAffineTransformMakeScale(0.1, 0.1)
                }
            }
            }) { (_) -> Void in
                //测试代码
//                UIView.animateWithDuration(0.25, animations: { () -> Void in
//                    for value in self.menuButtons{
//                        value.alpha = 1
//                        value.transform = CGAffineTransformIdentity
//                    }
//                })
                let model = self.modelArray![sender.tag]
                let type = NSClassFromString(model.className!)! as! UIViewController.Type
                let vc = type.init()
                self.targetVc?.presentViewController(UINavigationController(rootViewController: vc), animated: true, completion: { () -> Void in
                    self.removeFromSuperview()
                })
                
        }
        
        
        
    }
    private func itemsInfo()->[HJComposeMenuItemInfo]{
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        let arr = NSArray(contentsOfFile: path)!
        var tempArr:[HJComposeMenuItemInfo] = []
        for value in arr {
            let info = HJComposeMenuItemInfo(dict: value as! [String : AnyObject])
            tempArr.append(info)
        }
        return tempArr
    }
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for (i,value) in menuButtons.reverse().enumerate(){
            
            addAnimation(value, index: i, isUp: false)
        }

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.removeFromSuperview()
        }
        
        
    }
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        for (i,value) in menuButtons.enumerate(){
           addAnimation(value, index: i, isUp: true)
        }
    }
    private func addAnimation(value:HJComposeMenuButton, index:Int, isUp:Bool){
        let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        anim.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y + (isUp ? (-350) : 350)))
        anim.springBounciness = 8
        anim.springSpeed = 10
        anim.beginTime = Double(index) * 0.025 + CACurrentMediaTime()
        value.pop_addAnimation(anim, forKey: nil)
    }
    private lazy var sloganImage:UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
}
    